# This code is hosted on http://code.google.com/p/lenthorp/
# Freely available for use in applications, but should NOT be modified
# Email all comments to lenthorpresearch@gmail.com

import PricingEngineMod
from PricingEngineMod import *
reload(PricingEngineMod)

from math import exp, log, sqrt, pow
from scipy.stats import norm

# dS(t) = vol [delta * S(t) + (1 - delta) * S(0)] dW(t)

# Params: type, vol, delta, strike, tenor, rate, initial
class DisplaceDiffusionAnalytical(PricingEngine):

    def getPrice(self):
        if (self.currentStatus > 0):
            op = self.otherParams.p
            mp = self.modelParams.p
            p = dict(op.items() + mp.items())

            scaledInitial = p['initial'] / p['delta']
            scaledVol = p['vol'] * p['delta']
            
            d1 = (log(scaledInitial / (p['strike'] + (1.0-p['delta']) * scaledInitial)) + 0.5 * pow(scaledVol,2) * p['tenor']) / (scaledVol * sqrt(p['tenor']))
            d2 = d1 - (scaledVol * sqrt(p['tenor']))
            if (p['type'] == 'call'):
                val = exp(-p['rate'] * p['tenor']) * (scaledInitial * norm.cdf(d1) - (p['strike'] + (1.0-p['delta']) * scaledInitial ) * norm.cdf(d2))
            else:
                val = 0.0
               # val = (p['strike'] * exp(-p['rate'] * p['tenor']) * norm.cdf(-d2)) - (p['initial'] * exp(-p['div'] * p['tenor']) * norm.cdf(-d1))
            return val